from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api import deps
from app.schemas import customer
from app.database.models.erp import CustomerProfile, CustomerAddress
from app.database.models.base import User

router = APIRouter()

@router.get("/{customer_id}/addresses", response_model=List[customer.CustomerAddress])
def list_customer_addresses(
    customer_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取指定客户的所有地址"""
    try:
        # 检查客户是否存在
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == customer_id
        ).first()
        if not customer_obj:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 获取地址列表
        addresses = db.query(CustomerAddress).filter(
            CustomerAddress.customer_profile_id == customer_id
        ).all()
        return addresses
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/{customer_id}/addresses", response_model=customer.CustomerAddress)
def create_customer_address(
    *,
    db: Session = Depends(deps.get_db),
    customer_id: int,
    address_in: customer.CustomerAddressCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """为客户添加新的地址"""
    try:
        # 检查客户是否存在
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == customer_id
        ).first()
        if not customer_obj:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 创建新地址
        address = CustomerAddress(
            customer_profile_id=customer_id,
            **address_in.dict()
        )
        db.add(address)
        db.commit()
        db.refresh(address)
        return address
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/addresses/{address_id}", response_model=customer.CustomerAddress)
def update_customer_address(
    *,
    db: Session = Depends(deps.get_db),
    address_id: int,
    address_in: customer.CustomerAddressUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新客户地址"""
    try:
        # 获取地址记录
        address = db.query(CustomerAddress).filter(CustomerAddress.ID == address_id).first()
        if not address:
            raise HTTPException(status_code=404, detail="Address not found")

        # 检查权限
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == address.customer_profile_id
        ).first()
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新地址
        for field, value in address_in.dict(exclude_unset=True).items():
            setattr(address, field, value)

        db.add(address)
        db.commit()
        db.refresh(address)
        return address
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/addresses/{address_id}")
def delete_customer_address(
    *,
    db: Session = Depends(deps.get_db),
    address_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除客户地址"""
    try:
        # 获取地址记录
        address = db.query(CustomerAddress).filter(CustomerAddress.ID == address_id).first()
        if not address:
            raise HTTPException(status_code=404, detail="Address not found")

        # 检查权限
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == address.customer_profile_id
        ).first()
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 删除地址
        db.delete(address)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 